package cn.xingzitech.common.time;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 时间戳性能优化
 * @author Bulgat
 */
public class SystemClock {
    private static final String THREAD_NAME="system.clock";
    /**
     * 时间戳精度
     */
    private final long precision;
    private static final SystemClock MILLIS_CLOCK=new SystemClock(1);
    private final AtomicLong now;
    private SystemClock(long precision) {
        this.precision = precision;
        this.now=new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdate();
    }
    public static SystemClock millisClock(){
        return MILLIS_CLOCK;
    }

    private void scheduleClockUpdate(){
        ScheduledExecutorService scheduler =
                Executors.newSingleThreadScheduledExecutor(r -> {
            Thread thread = new Thread(r, THREAD_NAME);
            thread.setDaemon(true);
            return thread;
        });
        scheduler.scheduleAtFixedRate(
                ()->now.set(System.currentTimeMillis()),
                precision,
                precision,
                TimeUnit.MILLISECONDS
        );
    }

    /**
     * 获取当前时间
     * @return long
     */
    public long now(){
        return now.get();
    }

}
